<template>
  <div>
    <h1>宠物房间信息</h1>
    <div id="one" >
    <el-form :inline="true" :model="fromData" class="demo-form-inline">
      <el-form-item label="宠物房间号">
        <el-input v-model="fromData.num" placeholder="请输入宠物房间号"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSelect" 
        style="box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04)">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="success" @click="SubmitEvent" 
        style="box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04)">新增信息</el-button>
      </el-form-item>
      <div class="two">
      <el-form-item label="房间状态">
        <el-select v-model="value" clearable placeholder="请选择">
    <el-option
      v-for="item in options"
      :key="item.value"
      :label="item.label"
      :value="item.value">
    </el-option>
  </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onOption" 
        style="box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04)">查询</el-button>
      </el-form-item>
    </div>
    </el-form>
    
  </div>


  <!-- 添加信息表单 -->

  <el-dialog title="添加房间信息" :visible.sync="addDialogVisible" width="30%">
      <el-form :model="fromData" label-width="100px" >
        <!-- 表单上传头像区域 -->
        
        <el-form-item class="uploadPic">
        <el-upload
  style="margin-left: 80px;"
  list-type="picture-card"
  class="avatar-uploader"
  ref="uploadComponent"
  action="http://localhost:8081/img/upload"
  
  :show-file-list="false"
  :on-success="handleAvatarSuccess"
  :before-upload="beforeAvatarUpload">
  <img v-if="imageUrl" :src="imageUrl" class="avatarPic">
  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
        </el-form-item>
        <el-font style="color: tomato; margin-left: 30%;">(只限png格式，且小于1M！)</el-font>
        <el-form-item style="width: 100%; margin-left: 50px; margin-top: 10px;" label="宠物房间号" >
          <!-- <el-input v-model="fromData.num" placeholder="只能含有大写英文字母和数字！"></el-input> -->
          <template>
            <el-select v-model="fromData.num" placeholder="请选择">
              <el-option
                v-for="num in rooms_free"
                :key="num"
                :label="num"
                :value="num">
              </el-option>
            </el-select>
          </template>
        </el-form-item>
        <el-form-item style=" margin-left: 35px; margin-top: 10px;"   label="宠物房主">
          <el-input v-model.number="fromData.name" placeholder="不能为空！"></el-input>
        </el-form-item>
        <el-form-item style=" margin-left: 35px; margin-top: 10px;"  label="宠物性别">
          <!-- <el-input v-model="fromData.sex" placeholder="由于系统维护，0代表公，其余代表母！"></el-input> -->
          <template>
            <el-radio v-model="fromData.sex" :label="0">公</el-radio>
            <el-radio v-model="fromData.sex" :label="1">母</el-radio>
          </template>
        </el-form-item>
      
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button style="float: left;"  @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="uploadFile">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改信息表单 -->
    <el-dialog title="修改房间信息" :visible.sync="stuDialogVisible" width="30%">
      <el-form :model="fromData" label-width="100px">
        <el-form-item label="宠物房间号" >
          <el-input :disabled="true" v-model="fromData.num" placeholder="只能含有大写英文字母和数字！"></el-input>
        </el-form-item>
        <el-form-item label="宠物房主">
          <el-input v-model="fromData.name" placeholder="不能为空！"></el-input>
        </el-form-item>
        <el-form-item label="宠物性别">
          <!-- <el-input v-model="fromData.sex" placeholder="由于系统维护，0代表公，其余代表母！"></el-input> -->
          <template>
            <el-radio v-model="fromData.sex" :label="0">公</el-radio>
            <el-radio v-model="fromData.sex" :label="1">母</el-radio>
          </template>
        </el-form-item>
        <el-form-item label="房间状态">
          <template>
            <el-radio v-model="fromData.cond" label="空闲">空闲</el-radio>
            <el-radio v-model="fromData.cond" label="宝地有主啦">宝地有主啦</el-radio>
            <el-radio v-model="fromData.cond" label="宝地升级中">宝地升级中</el-radio>
          </template>
        </el-form-item>
      
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="stuDialogVisible = false" style="float: left;">取 消</el-button>
        <el-button type="primary" @click="updateRoom">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 数据表单设置 -->
    <el-table
      :data="dangqianyeData"
      style="width: 100%">
      <el-table-column
        label="序号" align='center'  prop="id"
        width="180">
      </el-table-column>
      <el-table-column
        label="宠物房间号" align='center'  prop="num"
        width="180">
      </el-table-column>
      <el-table-column
        label="宠物房主" align='center'  prop="name"
        >
      </el-table-column>

      <el-table-column
        label="主子萌照" align='center'  prop="pic"
        >
        <template slot-scope="scope">
          <el-image v-if="isDataLoaded"
           :src="scope.row.pic"
           style="width: 50px; height: 50px"
           fit="cover"
           :preview-src-list="[scope.row.pic]">

          </el-image>
        </template>
        </el-table-column>

      <el-table-column
        label="宠物性别" align='center'  prop="sex"
        >
        <!-- 根据int数据判断性别 -->
        <template slot-scope="scope">
          {{ scope.row.sex!=3 ? (scope.row.sex==0?'公':'母'): ''}}
        </template>

      </el-table-column>
      <el-table-column
        label="房间状态" align='center' prop="cond"
        >
      </el-table-column>
      <el-table-column align='center' label="操作">
        <template slot-scope="scope">
          <el-button
            style="border-radius: 30px ;box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04)" 
            type="warning" plain
            size="mini"
            @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button
            style="border-radius: 30px ;box-shadow: 0 2px 4px rgba(0, 0, 0, .12), 0 0 6px rgba(0, 0, 0, .04)" 
            size="mini"
            type="danger"
            @click="roomDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页设置 -->
     <div v-if="isDataLoaded">
    <el-pagination 
      background
      layout="prev, pager, next"
      @current-change="changepage"
      :page-count="maxPage"
      :total="totalRecords"
      >
    </el-pagination>
  </div>

  </div>
  </template>
  
  <!-- json数据传输 -->
  <script>
  import axios from 'axios';
  import { baseUrl } from '../store/baseUrl';
  export default {
    name: 'room',
    data () { 
      return {
        fromData: {
          name: '',
          type: '',
          num:'',
          sex: 0,
          pic: '',
          cond: ''
        },
        options: [{
          value: '空闲',
          label: '空闲'
        }, {
          value: '宝地有主啦',
          label: '宝地有主啦'
        }, {
          value: '宝地升级中',
          label: '宝地升级中'
        }],value: '',
        userList : [],
        imageUrl:'',
        isDataLoaded: false,
        addDialogVisible: false,
        stuDialogVisible: false,
        rooms_free: [],

        // 初始页码状态
        dangqianpage: 1,
      }
    },
    //分页方法
    computed: {
      dangqianyeData () {
        let qishi =(this.dangqianpage-1)*10
        console.log()
        return this.userList.slice(qishi,qishi+10)
    }
  },
  created () { 
    this.getData();
    // this.maxPage = Math.ceil(this.userList.length / 4)
  },

    // 用到的事件方法
    methods: {
      // 分页方法
      changepage (page) {
      this.dangqianpage = page;
    },
      // 修改信息（点击确定按钮提交修改后的数据给后端）
      updateRoom() {
        
        axios.post("http://localhost:8081/sysroom/update", this.fromData)  
            .then(response => {  
              this.stuDialogVisible = false;
              this.getdata();
            })  
            .catch(error => {  
              console.error('There was an error!', error);  
            });  
      },

      // 弹出修改表单，同时将后端已有的数据传给表单供其修改
      handleEdit(index, row) {
        this.fromData.name = row.name;
        this.fromData.cond = row.cond;
        this.fromData.num = row.num;
        this.fromData.sex = row.sex;
        this.fromData.pic = row.pic;
        
        this.stuDialogVisible = true;
      },

      // 获取数据库表单所有数据
      getdata() {  
          axios.get("http://localhost:8081/sysroom/list")  
            .then(response => {  
              this.userList = response.data.data;  
              this.total = response.data.data.length;
              this.selectRoomsFree();
              this.userList.forEach(user => {
            // 假设从后端返回的数据中，头像URL在一个叫做"avatar"的字段中
            user.pic = `${baseUrl}${user.pic}`;
          });

              this.maxPage = Math.ceil(this.userList.length / 10);
              // console.log("this.maxPage:",this.maxPage)
          // 设置数据加载标志
          this.isDataLoaded = true;

            })  
            .catch(error => {  
              console.error('There was an error!', error);  
            });  
        },

        // 根据房间号查询
      onSelect () { 

        
        let i= this.fromData.num;
        axios.get("http://localhost:8081/sysroom/getBynum?num="+i)  
            .then(response => {  
              console.log(response.data.data)
              this.userList = response.data.data;  
              this.total = response.data.data.length;
            })  
            .catch(error => {  
              console.error('There was an error!', error);  
            });  
      },

      // 根据房间状态查询
      onOption () { 
console.log(this.value)
        let i= this.value;
        axios.get("http://localhost:8081/sysroom/getcond?cond="+i)  
            .then(response => {  
              console.log(response.data.data)
              this.userList = response.data.data;  
              this.total = response.data.data.length;
    })  
    .catch(error => {  
      console.error('There was an error!', error);  
    });  
},

// 设置添加信息中房间号选择的判断方法，判断房间状态是空闲时将房间号传入选择项
      selectRoomsFree() {
        let rooms = [];
        this.userList.forEach(function(room, index) {
          if (room.cond == "空闲") {
              rooms.push(room.num)
            }
        })
        this.rooms_free = rooms;
      },
      // 新增信息方法
      SubmitEvent() {
        this.addDialogVisible = true;
      } ,
      handleAvatarSuccess(res, file) {
      // 使用后端返回的路径作为图像的URL
      this.imageUrl =`${baseUrl}/${res.data}`;
      this.fromData.pic = res.data;
      // 添加 avatar 字段到 formLabelAlign 对象中，使用后端返回的数据
      // this.fromData.avatar = res.data;
    },
    beforeAvatarUpload(file) {
        this.fromData.pic = file.name;
        const isPNG = file.type === 'image/png';
        const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isPNG) {
          this.$message.error('上传头像图片只能是 PNG 格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        return isPNG && isLt2M;
      },

    // 添加信息数据提交
      uploadFile() {
        axios.post("http://localhost:8081/sysroom/add", this.fromData)
        .then(res => {
          this.getdata();
        });
        /* console.log("pjb" + this.fromData.sex); */

        this.fromData.name = '';
        this.fromData.type = '';
        this.fromData.num = '';
        this.fromData.sex = 0;
        this.fromData.pic = '';
        this.addDialogVisible = false;
      },
      
      // 删除功能事件
      roomDelete (index,row) { 
        // 确认对话框，确认是否删除
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 删除数据
        let i= this.userList[index].id;
        axios.post("http://localhost:8081/sysroom/removeByid?id="+i)  
            .then(response => {  
              console.log(response.data.data)
              this.userList = response.data.data;  
              this.total = response.data.data.length;
              this.getdata();
      
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      });
       }).catch(() => {
        this.$message({
          type: 'warning',
          message: '已取消删除'
        });          
      });
        
      }
    },

    // ？？？？？？？
    mounted(){
      this.getdata();
    }
  }
  
  </script>

  <!-- 样式设置 -->
  <style scoped>
    .el-table {
      margin: auto;
      margin-top: 20px;
    }
    .avatarPic {
  width: 100%;
  height: 100%;
  object-fit:cover;
}
   .el-pagination{
    text-align: center;
    margin-top: 20px;
   }
   #one{
    width: 100%;
   }
   .two{
    float:right;
   }

   
  </style>